//
//  SFFileHandle.m
//  Test
//
//  Created by xueshan1 on 2018/11/15.
//  Copyright © 2018年 xueshan1. All rights reserved.
//

#import "SFFileHandle.h"

@implementation SFFileHandle

+ (BOOL)createTempFileWithPathComponent:(NSString *)pathComponent{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *path = [self tempPath];//先用个默认的
    if ([manager fileExistsAtPath:path]) {
        [manager removeItemAtPath:path error:nil];
    }
    return [manager createFileAtPath:path contents:nil attributes:nil];
}

+ (void)writeTempFileData:(NSData *)data{
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:[self tempPath]];
    [handle seekToEndOfFile];
    [handle writeData:data];
    [handle closeFile];
}

+ (NSData *)readTempFileDataWithOffset:(NSUInteger)offset length:(NSUInteger)length{
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:[self tempPath]];
    [handle seekToFileOffset:offset];
    return [handle readDataOfLength:length];
}

+ (void)saveTempFileWithFileName:(NSString *)name{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *cacheFolderPath = [self cacheFolderPath];
    if (![manager fileExistsAtPath:cacheFolderPath]) {
        [manager createDirectoryAtPath:cacheFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *cacheFilePath = [cacheFolderPath stringByAppendingPathComponent:name];
    
    BOOL success = [manager copyItemAtPath:[self tempPath] toPath:cacheFilePath error:nil];
    
    NSLog(@"cache file :%@",success?@"success":@"fail");
}

+ (NSString *)existCacheFileWithUrl:(NSURL *)url{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *cacheFolderPath = [self cacheFolderPath];
    NSString *cacheFilePath = [cacheFolderPath stringByAppendingPathComponent:url.absoluteString.lastPathComponent];
    if ([manager fileExistsAtPath:cacheFilePath]) {
        return cacheFilePath;
    }
    return nil;
}

+ (NSString *)tempPath{
    NSString *tmp = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp11112.mp3"];
    return tmp;
}

+ (NSString *)cacheFolderPath{
    NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    return [libraryPath stringByAppendingPathComponent:@"AudioCache"];
}


@end
